// pages/talent/talent.ts

// 类型定义
interface Position {
  x: number;
  y: number;
}

interface TalentNode {
  id: number;
  name: string;
  description: string;
  maxLevel: number;
  currentLevel: number;
  position: Position;
  requirements: number[];//上一级天赋点
  nextId?: number[];//下一级天赋点
  effects: string[];
  icon: string;
  pathId: number;
  canAllocate?:boolean;//是否可以加点
}

interface TalentPath {
  id: number;
  name: string;
  color: string;
  talents: TalentNode[];
}

interface PageData {
  availablePoints: number;
  totalPoints: number;
  activePath: number;
  scale: number;
  selectedTalent: TalentNode | null;
  offsetX: number;
  offsetY: number;
  isDragging: boolean;
  lastTouchX: number;
  lastTouchY: number;
  talentPaths: TalentPath[];
  currentPaths:TalentPath[];
}

Page({
  data: {
    availablePoints: 10,
    totalPoints: 10,
    activePath: 0,
    scale: 1.0,
    selectedTalent: null,
    offsetX: 0,
    offsetY: 0,
    isDragging: false,
    lastTouchX: 0,
    lastTouchY: 0,
    talentPaths: [
      {
        id: 0,
        name: "攻击天赋",
        color: "#e94560",
        talents: [] as TalentNode[]
      },
      {
        id: 1,
        name: "防御天赋",
        color: "#4ecca3",
        talents: [] as TalentNode[]
      },
      {
        id: 2,
        name: "辅助天赋",
        color: "#f9a828",
        talents: [] as TalentNode[]
      }
    ]
  } as PageData,

  onLoad() {
    this.initTalentTree();
    // 等待Canvas初始化完成
    setTimeout(() => {
      this.drawTalentTree();
    }, 100);
  },

  onReady() {
    // 确保Canvas已准备好
    this.drawTalentTree();
  },

  // 初始化天赋树数据
  initTalentTree() {
    const attackTalents: TalentNode[] = [
      {
        id: 101,
        name: "强力打击",
        description: "增加物理攻击力",
        maxLevel: 5,
        currentLevel: 0,
        position: { x: 100, y: 100 },
        requirements: [],
        effects: ["物理攻击+5", "暴击率+2%"],
        icon: "/images/attack.png",
        pathId: 0
      },
      {
        id: 102,
        name: "精准射击",
        description: "提高远程攻击精度",
        maxLevel: 3,
        currentLevel: 0,
        position: { x: 250, y: 100 },
        requirements: [],
        effects: ["远程伤害+8%", "命中率+5%"],
        icon: "/images/ranged.png",
        pathId: 0
      },
      {
        id: 103,
        name: "致命一击",
        description: "大幅提升暴击伤害",
        maxLevel: 1,
        currentLevel: 0,
        position: { x: 175, y: 250 },
        requirements: [101, 102],
        effects: ["暴击伤害+50%"],
        icon: "/images/critical.png",
        pathId: 0
      },
      {
        id: 104,
        name: "狂暴姿态",
        description: "进入狂暴状态提升攻击速度",
        maxLevel: 3,
        currentLevel: 0,
        position: { x: 400, y: 150 },
        requirements: [101],
        effects: ["攻击速度+15%", "移动速度+10%"],
        icon: "/images/berserk.png",
        pathId: 0
      }
    ];

    const defenseTalents: TalentNode[] = [
      {
        id: 201,
        name: "钢铁皮肤",
        description: "提升物理防御力",
        maxLevel: 5,
        currentLevel: 0,
        position: { x: 100, y: 100 },
        requirements: [],
        effects: ["物理防御+10", "伤害减免+3%"],
        icon: "/images/defense.png",
        pathId: 1
      },
      {
        id: 202,
        name: "魔法护盾",
        description: "提高魔法抗性",
        maxLevel: 3,
        currentLevel: 0,
        position: { x: 250, y: 100 },
        requirements: [],
        effects: ["魔法抗性+15%", "状态抗性+10%"],
        icon: "/images/magic.png",
        pathId: 1
      },
      {
        id: 203,
        name: "生命强化",
        description: "提升最大生命值",
        maxLevel: 5,
        currentLevel: 0,
        position: { x: 175, y: 250 },
        requirements: [201],
        effects: ["生命值+100", "生命恢复+5"],
        icon: "/images/health.png",
        pathId: 1
      }
    ];

    const supportTalents: TalentNode[] = [
      {
        id: 301,
        name: "治疗精通",
        description: "增强治疗效果",
        maxLevel: 5,
        currentLevel: 0,
        position: { x: 100, y: 100 },
        requirements: [],
        effects: ["治疗效果+20%", "治疗范围+10%"],
        icon: "/images/heal.png",
        pathId: 2
      },
      {
        id: 302,
        name: "团队鼓舞",
        description: "提升团队属性",
        maxLevel: 2,
        currentLevel: 0,
        position: { x: 250, y: 100 },
        requirements: [],
        effects: ["全队攻击+5%", "全队防御+5%"],
        icon: "/images/buff.png",
        pathId: 2
      },
      {
        id: 303,
        name: "复活精通",
        description: "提升复活技能效果",
        maxLevel: 1,
        currentLevel: 0,
        position: { x: 175, y: 250 },
        requirements: [301, 302],
        effects: ["复活后生命值+50%", "复活冷却-30%"],
        icon: "/images/revive.png",
        pathId: 2
      }
    ];

    this.setData({
      'talentPaths[0].talents': attackTalents,
      'talentPaths[1].talents': defenseTalents,
      'talentPaths[2].talents': supportTalents
    });
  },

  // 绘制天赋树
  drawTalentTree() {
    const ctx = wx.createCanvasContext('talentCanvas');
    const { offsetX, offsetY, scale, activePath, talentPaths } = this.data;
    
    // 清空画布
    ctx.clearRect(0, 0, 500, 500);
    
    // 绘制背景
    ctx.setFillStyle('#1a1a2e');
    ctx.fillRect(0, 0, 500, 500);
    
    // 绘制网格
    this.drawGrid(ctx);
    
    const currentPath = talentPaths[activePath];
    
    // 绘制连接线
    this.drawConnections(ctx, currentPath.talents, offsetX, offsetY, scale);
    
    // 绘制天赋节点
    currentPath.talents.forEach(talent => {
      this.drawTalentNode(ctx, talent, offsetX, offsetY, scale);
    });
    
    ctx.draw();
  },

  // 绘制网格背景
  drawGrid(ctx: WechatMiniprogram.CanvasContext) {
    ctx.setStrokeStyle('rgba(255, 255, 255, 0.1)');
    ctx.setLineWidth(1);
    
    for (let x = 0; x <= 500; x += 50) {
      ctx.beginPath();
      ctx.moveTo(x, 0);
      ctx.lineTo(x, 500);
      ctx.stroke();
    }
    
    for (let y = 0; y <= 500; y += 50) {
      ctx.beginPath();
      ctx.moveTo(0, y);
      ctx.lineTo(500, y);
      ctx.stroke();
    }
  },

  // 绘制天赋节点之间的连接线
  drawConnections(
    ctx: WechatMiniprogram.CanvasContext, 
    talents: TalentNode[], 
    offsetX: number, 
    offsetY: number, 
    scale: number
  ) {
    ctx.setStrokeStyle('#4ecca3');
    ctx.setLineWidth(2);
    
    talents.forEach(talent => {
      if (talent.requirements && talent.requirements.length > 0) {
        talent.requirements.forEach(reqId => {
          const requirement = talents.find(t => t.id === reqId);
          if (requirement) {
            const startX = requirement.position.x * scale + offsetX;
            const startY = requirement.position.y * scale + offsetY;
            const endX = talent.position.x * scale + offsetX;
            const endY = talent.position.y * scale + offsetY;
            
            ctx.beginPath();
            ctx.moveTo(startX, startY);
            ctx.lineTo(endX, endY);
            ctx.stroke();
          }
        });
      }
    });
  },

  // 绘制单个天赋节点
  drawTalentNode(
    ctx: WechatMiniprogram.CanvasContext, 
    talent: TalentNode, 
    offsetX: number, 
    offsetY: number, 
    scale: number
  ) {
    const x = talent.position.x * scale + offsetX;
    const y = talent.position.y * scale + offsetY;
    const radius = 25 * scale;
    
    // 检查是否可以分配
    const canAllocate = this.checkCanAllocate(talent);
    
    // 设置节点颜色
    if (talent.currentLevel > 0) {
      ctx.setFillStyle('#4ecca3'); // 已激活 - 绿色
    } else if (canAllocate) {
      ctx.setFillStyle('#f9a828'); // 可激活 - 橙色

    } else {
      ctx.setFillStyle('#555'); // 不可激活 - 灰色
    }
    
    // 绘制节点背景
    ctx.beginPath();
    ctx.arc(x, y, radius, 0, 2 * Math.PI);
    ctx.fill();
    
    // 绘制节点边框
    ctx.setStrokeStyle('#fff');
    ctx.setLineWidth(2);
    ctx.stroke();
    
    // 绘制节点图标（模拟）
    ctx.setFillStyle('#fff');
    ctx.setFontSize(14 * scale);
    ctx.setTextAlign('center');
    ctx.setTextBaseline('middle');
    ctx.fillText('★', x, y);
    
    // 绘制等级文本
    if (talent.maxLevel > 1) {
      ctx.setFillStyle('#fff');
      ctx.setFontSize(10 * scale);
      ctx.setTextAlign('center');
      ctx.fillText(
        `${talent.currentLevel}/${talent.maxLevel}`,
        x,
        y + radius + 12 * scale
      );
    }
  },

  // 检查天赋是否可以分配
  checkCanAllocate(talent: TalentNode): boolean {
    if (talent.currentLevel >= talent.maxLevel) return false;
    if (this.data.availablePoints <= 0) return false;
    
    // 检查前置要求
    if (talent.requirements && talent.requirements.length > 0) {
      const currentPath = this.data.talentPaths[this.data.activePath];
      for (const reqId of talent.requirements) {
        const requirement = currentPath.talents.find(t => t.id === reqId);
        if (!requirement || requirement.currentLevel === 0) {
          return false;
        }
      }
    }
    
    return true;
  },

  // 触摸事件处理
  onTouchStart(e: WechatMiniprogram.TouchEvent) {
    console.log("touch_start")
    const touch = e.touches[0];
    this.setData({
      isDragging: true,
      lastTouchX: touch.clientX,
      lastTouchY: touch.clientY
    });
  },

  onTouchMove(e: WechatMiniprogram.TouchEvent) {
    console.log("touch_move")
    if (!this.data.isDragging) return;
    
    const touch = e.touches[0];
    const deltaX = touch.clientX - this.data.lastTouchX;
    const deltaY = touch.clientY - this.data.lastTouchY;
    
    this.setData({
      offsetX: this.data.offsetX + deltaX,
      offsetY: this.data.offsetY + deltaY,
      lastTouchX: touch.clientX,
      lastTouchY: touch.clientY
    });
    
    this.drawTalentTree();
  },

  onTouchEnd(e:any) {
    console.log("touch_end",e)
    this.setData({ isDragging: false });
    
    // // 检查是否点击了天赋节点

    this.checkTalentClick(e.changedTouches[0]);

  },

  // 检查点击位置是否在天赋节点上
  checkTalentClick(touch: WechatMiniprogram.Touch) {
    console.log("检查点击位置是否在天赋节点上",this.data)
    const { offsetX, offsetY, scale, activePath, talentPaths } = this.data;
    const currentPath = talentPaths[activePath];
    
    // 获取Canvas的位置信息
    const query = wx.createSelectorQuery();
    query.select('.talent-canvas').boundingClientRect((rect: any) => {
      if (!rect) return;
      
      const canvasLeft = rect.left;
      const canvasTop = rect.top;
      
      for (const talent of currentPath.talents) {
        const x = talent.position.x * scale + offsetX;
        const y = talent.position.y * scale + offsetY;
        const radius = 25 * scale;
        
        // 计算相对于Canvas的点击位置
        const clickX = touch.clientX - canvasLeft;
        const clickY = touch.clientY - canvasTop;
        
        // 计算点击位置与节点中心的距离
        const distance = Math.sqrt(
          Math.pow(clickX - x, 2) + Math.pow(clickY - y, 2)
        );
        console.log("点击位置：",clickX,clickY)
        console.log("节点中心位置",x,y)
        console.log("距离节点中心",distance)
        console.log("radius",radius)
        console.log("talent",talent)
        if (distance <= radius) {
          this.setData({ selectedTalent: talent });
          break;
        }

      }
    }).exec();

  },

  // 分配天赋点
  allocatePoint() {
    const { selectedTalent } = this.data;
    if (!selectedTalent || !this.checkCanAllocate(selectedTalent)) {
      wx.showToast({
        title: '无法分配天赋点',
        icon: 'none'
      });
      return;
    }
    
    const pathIndex = this.data.activePath;
    const talentIndex = this.data.talentPaths[pathIndex].talents
      .findIndex(t => t.id === selectedTalent.id);
    
    if (talentIndex !== -1) {
      const updatePath = `talentPaths[${pathIndex}].talents[${talentIndex}].currentLevel`;
      this.setData({
        [updatePath]: selectedTalent.currentLevel + 1,
        availablePoints: this.data.availablePoints - 1
      });
      
      // 更新选中的天赋数据
      const updatedTalent = {
        ...selectedTalent,
        currentLevel: selectedTalent.currentLevel + 1
      };
      this.setData({
        selectedTalent: updatedTalent
      });
      
      this.drawTalentTree();
      
      wx.showToast({
        title: '天赋点分配成功',
        icon: 'success'
      });
    }
  },

  // 移除天赋点
  deallocatePoint() {
    const { selectedTalent } = this.data;
    if (!selectedTalent || selectedTalent.currentLevel <= 0) {
      wx.showToast({
        title: '无法移除天赋点',
        icon: 'none'
      });
      return;
    }
    
    // 检查是否有后续天赋依赖此天赋
    if (this.hasDependentTalents(selectedTalent)) {
      wx.showToast({
        title: '有后续天赋依赖此天赋',
        icon: 'none'
      });
      return;
    }
    
    const pathIndex = this.data.activePath;
    const talentIndex = this.data.talentPaths[pathIndex].talents
      .findIndex(t => t.id === selectedTalent.id);
    
    if (talentIndex !== -1) {
      const updatePath = `talentPaths[${pathIndex}].talents[${talentIndex}].currentLevel`;
      this.setData({
        [updatePath]: selectedTalent.currentLevel - 1,
        availablePoints: this.data.availablePoints + 1
      });
      
      // 更新选中的天赋数据
      const updatedTalent = {
        ...selectedTalent,
        currentLevel: selectedTalent.currentLevel - 1
      };
      this.setData({
        selectedTalent: updatedTalent
      });
      
      this.drawTalentTree();
      
      wx.showToast({
        title: '天赋点移除成功',
        icon: 'success'
      });
    }
  },

  // 检查是否有其他天赋依赖此天赋
  hasDependentTalents(talent: TalentNode): boolean {
    const currentPath = this.data.talentPaths[this.data.activePath];
    return currentPath.talents.some(t => 
      t.requirements && 
      t.requirements.includes(talent.id) && 
      t.currentLevel > 0
    );
  },

  // 切换天赋路径
  switchPath(e:any) {
    const pathId = parseInt(e.currentTarget.dataset.path as string);
    this.setData({ 
      activePath: pathId,
      offsetX: 0,
      offsetY: 0,
      selectedTalent: null
    });
    this.drawTalentTree();
  },

  // 缩放控制
  zoomIn() {
    const newScale = Math.min(this.data.scale + 0.1, 2.0);
    this.setData({ scale: newScale });
    this.drawTalentTree();
  },

  zoomOut() {
    const newScale = Math.max(this.data.scale - 0.1, 0.5);
    this.setData({ scale: newScale });
    this.drawTalentTree();
  },

  // 关闭详情弹窗
  closeDetail() {
    this.setData({ selectedTalent: null });
  },

  // 重置所有天赋
  resetAll() {
    wx.showModal({
      title: '确认重置',
      content: '确定要重置所有天赋点吗？',
      success: (res) => {
        if (res.confirm) {
          const { talentPaths, totalPoints } = this.data;
          
          // 重置所有天赋点的当前等级
          talentPaths.forEach(path => {
            path.talents.forEach(talent => {
              talent.currentLevel = 0;
            });
          });
          
          this.setData({
            talentPaths,
            availablePoints: totalPoints,
            selectedTalent: null
          });
          
          this.drawTalentTree();
          
          wx.showToast({
            title: '重置成功',
            icon: 'success'
          });
        }
      }
    });
  },

  // 保存天赋配置
  saveTalentBuild() {
    const { talentPaths, activePath } = this.data;
    const currentBuild = {
      path: activePath,
      talents: talentPaths[activePath].talents.map(t => ({
        id: t.id,
        level: t.currentLevel
      }))
    };
    
    // 保存到本地存储
    wx.setStorageSync('currentTalentBuild', currentBuild);
    
    wx.showToast({
      title: '配置已保存',
      icon: 'success'
    });
  },

  // 加载天赋配置
  loadTalentBuild() {
    const savedBuild = wx.getStorageSync('currentTalentBuild');
    if (!savedBuild) {
      wx.showToast({
        title: '没有保存的配置',
        icon: 'none'
      });
      return;
    }
    
    this.resetAll();
    
    // 延迟加载以确保重置完成
    setTimeout(() => {
      const { talentPaths } = this.data;
      let pointsUsed = 0;
      
      // 应用保存的天赋配置
      savedBuild.talents.forEach((savedTalent: any) => {
        const path = talentPaths[savedBuild.path];
        const talent = path.talents.find(t => t.id === savedTalent.id);
        if (talent && savedTalent.level <= talent.maxLevel) {
          talent.currentLevel = savedTalent.level;
          pointsUsed += savedTalent.level;
        }
      });
      
      this.setData({
        talentPaths,
        activePath: savedBuild.path,
        availablePoints: this.data.totalPoints - pointsUsed,
        selectedTalent: null
      });
      
      this.drawTalentTree();
      
      wx.showToast({
        title: '配置已加载',
        icon: 'success'
      });
    }, 500);
  }
});